package com.zplh.zplh_android_yk.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.zplh.zplh_android_yk.R;
import com.zplh.zplh_android_yk.TaskManager;
import com.zplh.zplh_android_yk.ui.OtherActivity;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import zplh.com.commonlibrary.utils.LogUtils;

/**
 * 此服务主要是用来执行定时任务的发放 每10分钟判断一次定时任务
 * 此服务还进行任务执行的检查 检查任务状态
 * 在此服务执行后的半分钟之后 将开始发送任务
 * Created by yong hao zeng on 2018/7/4.
 */
public class TaskSender extends Service {
private static final String TAG = TaskSender.class.getSimpleName();
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.d(TAG,"onStartCommand" );
        Notification notification = createNotification();
        startForeground(110,notification );
        startAppTask();
        checkTimeTask();
        return super.onStartCommand(intent, flags, startId);
    }

    private void startAppTask() {
        if (!TaskManager.getInstance().isLoopTask) {
            TaskManager.getInstance().loopTask();
        }
    }


    private Notification createNotification() {
        Notification.Builder builder = new Notification.Builder(getApplicationContext());

        Intent nfIntent = new Intent(this,OtherActivity.class);

        builder.setContentIntent(PendingIntent.getActivity(this,0,nfIntent,0))
                .setSmallIcon(R.drawable.taskmonitor)
                .setContentTitle("云控助手")
                .setContentText("助手正在努力工作")
                .setWhen(System.currentTimeMillis());

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND;
        return notification;
    }

    /**
     * 没10分钟检查一次定时
     */
    @SuppressLint("CheckResult")
    private void checkTimeTask() {
        Observable.interval(600000, TimeUnit.MILLISECONDS).
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    LogUtils.d(TAG,"寻找定时任务");
                    TaskManager.getInstance().findApplyTaskByTime();
                });

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



}
